package com.jielihaofeng.chat.localcache.impl;

import com.jielihaofeng.chat.constants.LocalCacheType;
import com.jielihaofeng.chat.convert.ChatGroupConvert;
import com.jielihaofeng.chat.entity.ChatGroupEntity;
import com.jielihaofeng.chat.entity.ChatGroupLocalCacheEntity;
import com.jielihaofeng.chat.localcache.AbstractTimedRefreshLocalCache;
import com.jielihaofeng.chat.service.ChatGroupService;
import com.jielihaofeng.framework.common.entity.BaseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Description: a simple description
 *
 * @author xieli
 * @version 1.0
 * @date 2022/10/3 9:31 PM
 * @since JDK 1.8
 */
@Slf4j
public class ChatGroupLocalCache extends AbstractTimedRefreshLocalCache<Long, ChatGroupLocalCacheEntity> {

    @Autowired
    private ChatGroupService chatGroupService;

    @Override
    protected ChatGroupLocalCacheEntity loadFromDB(Long id) {
        ChatGroupEntity chatGroupEntity = chatGroupService.getById(id);
        return ChatGroupConvert.INSTANCE.convert2LocalCacheEntity(chatGroupEntity);
    }

    @Override
    protected Map<Long, ChatGroupLocalCacheEntity> loadAllFromDB(List<Long> ids) {
        List<ChatGroupEntity> chatGroupEntities = chatGroupService.listByIds(ids);
        if (CollectionUtils.isEmpty(chatGroupEntities)) {
            log.warn("[{}] ChatGroupEntity is empty. ids:{}.", getClass().getSimpleName(), ids.toString());
            return new HashMap<>();
        }
        return chatGroupEntities.stream().collect(Collectors.toMap(BaseEntity::getId, ChatGroupConvert.INSTANCE::convert2LocalCacheEntity, (v2, v1) -> v2));
    }

    @Override
    protected Map<Long, ChatGroupLocalCacheEntity> loadAll() {
        List<ChatGroupEntity> chatGroupEntities = chatGroupService.list();
        if (CollectionUtils.isEmpty(chatGroupEntities)) {
            log.warn("[{}] ChatGroupEntity is empty.", getClass().getSimpleName());
            return new HashMap<>();
        }
        return chatGroupEntities.stream().collect(Collectors.toMap(BaseEntity::getId, ChatGroupConvert.INSTANCE::convert2LocalCacheEntity, (v2, v1) -> v2));
    }

    @Override
    protected boolean isLoadAll() {
        return true;
    }

    @Override
    protected long maximumSize() {
        return 1000;
    }

    @Override
    protected long refreshPeriodMinutes() {
        return 60 * 12;
    }

    @Override
    public String cacheType() {
        return LocalCacheType.CHAT_GROUP.name();
    }
}
